package org.webdb.webapp.resteasy;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.jboss.resteasy.spi.Registry;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.picocontainer.web.PicoScopedContainers;
import org.picocontainer.web.ScopedContainers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ResteasyPicoBootstrap implements ServletContextListener {

    private PicoScopedContainers sc;
    private static final Logger logger = LoggerFactory
            .getLogger("PicoRestEasy");

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // TODO Auto-generated method stub

    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        logger.info("Starting...");
        ServletContext context = sce.getServletContext();
        ScopedContainers sc = (ScopedContainers) context
                .getAttribute(ScopedContainers.class.getName());

        if (sc == null)
            throw new IllegalStateException(
                    "No PicoScopedContainers in ServletContext!");
        this.sc = new PicoScopedContainers(sc);

        PicoScanner scanner = new PicoScanner();
        scanApplicationContext(scanner, sce.getServletContext());
        scanRequestContext(scanner, sce.getServletContext());
        logger.info("Started.");
    }

    private void scanApplicationContext(PicoScanner scanner,
            ServletContext servletContext) {
        ResteasyProviderFactory factory = (ResteasyProviderFactory) servletContext
                .getAttribute(ResteasyProviderFactory.class.getName());

        scanner.scanProviders(factory, sc.getApplicationContainer().getParent());
        scanner.scanProviders(factory, sc.getApplicationContainer());
    }

    private void scanRequestContext(PicoScanner scanner,
            ServletContext servletContext) {
        Registry registry = (Registry) servletContext
                .getAttribute(Registry.class.getName());
        scanner.scanResources(registry, sc.getRequestContainer());
    }

}
